<!--
 * @Description: 
 * @Author: Wang Su
 * @Date: 2024-01-09 15:49:21
 * @LastEditors: Wang Su
 * @LastEditTime: 2024-01-10 14:47:43
-->
<template>
    <div class="map">
        <div class="serach">
            <map-search @share_id="shareId" @input_val="inputVal" @select_val="selectVal" @change_theme="changeTheme" />
        </div>
        <div class="map_container" id="container"></div>
    </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import mapSearch from "./search.vue";
import cityJson from "../../assets/area.json";
window._AMapSecurityConfig = {
    securityJsCode: "e3a924a19587ffe88c620e4a6da87bc3",
};
export default {
    name: "mapContainer",
    components: { mapSearch },
    mixins: [],
    props: {},
    data() {
        return {
            map: null,
            autoOptions: {
                input: "",
            },
            auto: null,
            AMap: null,
            placeSearch: null,
            searchPlaceInput: "",
            polygons: [],
            positions: [],
            //地图样式配置
            inintMapStyleConfig: {
                //设置地图容器id
                viewMode: "2D", //是否为3D地图模式
                zoom: 15, //初始化地图级别
                rotateEnable: true, //是否开启地图旋转交互 鼠标右键 + 鼠标画圈移动 或 键盘Ctrl + 鼠标左键画圈移动
                pitchEnable: true, //是否开启地图倾斜交互 鼠标右键 + 鼠标上下移动或键盘Ctrl + 鼠标左键上下移动
                mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
                center: [118.796877, 32.060255], //初始化地图中心点位置
            },
            //地图配置
            mapConfig: {
                key: "d27d71e962d2ddbfcea15089cddca22c", // 申请好的Web端开发者Key，首次调用 load 时必填
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: [
                    "AMap.AutoComplete",
                    "AMap.PlaceSearch",
                    "AMap.Geocoder",
                    "AMap.DistrictSearch",
                ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            },
            // 实例化DistrictSearch配置
            districtSearchOpt: {
                subdistrict: 1, //获取边界不需要返回下级行政区
                extensions: "all", //返回行政区边界坐标组等具体信息
            },
            icon: {
                type: "image",
                image: require("../../assets/equip.png"),
                size: [15, 21],
                anchor: "bottom-center",
                fitZoom: [14, 20], // Adjust the fitZoom range for scaling
                scaleFactor: 2, // Zoom scale factor
                maxScale: 2, // Maximum scale
                minScale: 1 // Minimum scale
            }
        };
    },
    computed: {},

    created() {
        this.initMap();
    },
    mounted() {

    },
    methods: {
        //初始化地图
        async initMap() {
            this.AMap = await AMapLoader.load(this.mapConfig);
            this.map = new AMap.Map("container", this.inintMapStyleConfig);
            //根据地理位置查询经纬度
            this.positions = await Promise.all(cityJson.map(async item => {
                try {
                    const dot = await this.queryGeocodes(item.cityName, this.AMap);
                    return {
                        ...item,
                        dot: dot
                    };
                } catch (error) {

                }
            }));

            //poi查询
            this.addMarker();
            //显示南京的区域
            this.drawBounds("江苏省");

        },

        //查询地理位置
        async queryGeocodes(newValue, AMap) {
            return new Promise((resolve, reject) => {
                //加载行政区划插件
                const geocoder = new AMap.Geocoder({
                    // 指定返回详细地址信息，默认值为true
                    extensions: 'all'
                });
                // 使用地址进行地理编码
                geocoder.getLocation(newValue, (status, result) => {
                    if (status === 'complete' && result.geocodes.length) {
                        const geocode = result.geocodes[0];
                        const latitude = geocode.location.lat;
                        const longitude = geocode.location.lng;
                        resolve([longitude, latitude]);
                    } else {
                        reject('无法获取该地址的经纬度');
                    }
                });
            });
        },
        //结合输入提示进行POI搜索
        shareId(val) {
            this.autoOptions.input = val;
        },
        //根据设备搜索
        inputVal(val) {
            if (val?.length === 0) {
                //poi查询
                this.addMarker();
                //显示南京的区域
                this.drawBounds("江苏省");
                return;
            }
            var position = val
            this.icon.size = [12, 18]
            this.map.setCenter(position)
            this.queryPoI()
            this.map.setZoom(12, true, 1);
        },
        //修改主题
        changeTheme(val) {
            const styleName = "amap://styles/" + val;
            this.map.setMapStyle(styleName);
        },
        //区域搜索
        selectVal(val) {
            if (val && val.length > 0) {
                let vals = val[val?.length - 1];
                vals = vals.replace(/\s+/g, '');
                this.icon.size = [12, 18]
                this.queryPoI()
                this.placeSearch.search(vals);
                this.drawBounds(vals);
                this.map.setZoom(15, true, 1);
            }
        },

        //添加marker
        addMarker() {
            const icon = this.icon
            let layer = new this.AMap.LabelsLayer({
                zooms: [3, 20],
                zIndex: 1000,
                collision: false,
            });
            // 将图层添加到地图
            this.map.add(layer);
            // 普通点
            let markers = [];
            this.positions.forEach((item) => {
                const content = `
                <div class="custom-info-window">
                    <div class="info-window-header"><b>${item.cityName}</b></div>
                    <div class="info-window-body">
                        <div>边设备数 : ${item.edgNum} 台</div>
                        <div>端设备数 : ${item.endNum} 台</div>
                    </div>
                </div>
            `;
                let labelMarker = new AMap.LabelMarker({
                    position: item.dot,
                    icon: icon,
                    rank: 1, //避让优先级
                });
                const infoWindow = new AMap.InfoWindow({
                    content: content, //传入字符串拼接的 DOM 元素
                    anchor: "top-left",
                });
                labelMarker.on('mouseover', () => {
                    infoWindow.open(this.map, item.dot);
                });

                labelMarker.on('mouseout', () => {
                    infoWindow.close();
                });
                labelMarker.on('click', () => {
                    this.icon.size = [12, 18]
                    this.map.setCenter(item.dot)
                    this.queryPoI()
                    this.map.setZoom(15, true, 1);
                })
                markers.push(labelMarker);
            });
            // 一次性将海量点添加到图层
            layer.add(markers);
        },

        //POI查询
        queryPoI() {
            this.auto = new this.AMap.AutoComplete(this.autoOptions);
            this.placeSearch = new this.AMap.PlaceSearch({
                map: this.map,
            }); //构造地点查询类
            this.auto.on("select", this.select);

            this.addMarker();
        },
        //选择数据
        select(e) {
            this.placeSearch.setCity(e.poi.adcode);
            this.placeSearch.search(e.poi.name); //关键字查询查询
            this.map.setZoom(15, true, 1);
        },

        // 行政区边界绘制
        drawBounds(newValue) {
            //加载行政区划插件
            if (!this.district) {
                this.map.plugin(["AMap.DistrictSearch"], () => {
                    this.district = new AMap.DistrictSearch(this.districtSearchOpt);
                });
            }
            //行政区查询
            this.district.search(newValue, (_status, result) => {
                if (Object.keys(result).length === 0) {
                    this.$message.warning("未查询到该地区数据");
                    return
                }
                if (this.polygons != null) {
                    this.map.remove(this.polygons); //清除上次结果
                    this.polygons = [];
                }
                //绘制行政区划
                result?.districtList[0]?.boundaries?.length > 0 &&
                    result.districtList[0].boundaries.forEach((item) => {
                        let polygon = new AMap.Polygon({
                            strokeWeight: 1,
                            path: item,
                            fillOpacity: 0.1,
                            fillColor: "#22886f",
                            strokeColor: "#22886f",
                        });
                        this.polygons.push(polygon);

                    });
                this.map.add(this.polygons);
                this.map.setFitView(this.polygons); //视口自适应

            });
        },
    },
};
</script>
<style lang="less" scoped>
.map {
    width: 100%;
    height: 100%;

    position: relative;

    .map_container {
        width: 100%;
        height: 100%;
    }

    .serach {
        position: absolute;
        z-index: 33;
        left: 20px;
        top: 10px;
    }
}
</style>
<style>
.amap-logo {
    right: 0 !important;
    left: auto !important;
    display: none !important;
}

.amap-copyright {
    right: 70px !important;
    left: auto !important;
    opacity: 0 !important;
}

/* 自定义 infoWindow 样式 */
.custom-info-window {
    font-family: Arial, sans-serif;
    padding: 10px;
    border-radius: 8px;
    background-color: #ffffff;
    max-width: 250px;
}
</style>